package dao.impl;

import dao.IMajorDao;
import domain.Major;
import util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MajorDaoImpl implements IMajorDao {
    @Override
    public int addMajor(Major major) throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        String sql = "insert into majors_classes (name, parent_id) values (?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        int i = 1;
        preparedStatement.setString(i++, major.getName());
        preparedStatement.setInt(i, major.getParentId());

        int result = preparedStatement.executeUpdate();

        preparedStatement.close();
        conn.close();
        return result;
    }

    @Override
    public int delMajor(Major major) throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        String sql = "delete from majors_classes where id = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1,major.getId());
        int result = preparedStatement.executeUpdate();
        preparedStatement.close();
        conn.close();
        return result;
    }

    @Override
    public int updMajor(Major major) throws SQLException {
        Connection conn = JdbcUtils.getConnection();
        String sql = "update majors_classes set name=?,parent_id=? where id=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,major.getName());
        preparedStatement.setInt(2,major.getParentId());
        preparedStatement.setInt(3,major.getId());
        int result = preparedStatement.executeUpdate();
        preparedStatement.close();
        conn.close();
        return result;
    }

    @Override
    public List<Major> selMajor(Major major) throws SQLException {
        List<Major> signRecordList = new ArrayList<>();
        Connection conn = JdbcUtils.getConnection();
        String sql = "select * from majors_classes";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        ResultSet rs = preparedStatement.executeQuery();
        while (rs.next()) {
                Major major1= new Major();
                major1.setId(rs.getInt("id"));
                major1.setName(rs.getString("name"));
                major1.setParentId(rs.getInt("parent_id"));
                signRecordList.add(major1);
            }
        preparedStatement.close();
        conn.close();
        return signRecordList;
    }

}
